<template>
  <div class="entryFrom">
    <el-form
      style="margin-left: 60px"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-row style="width: 100%">
        <el-col style="width: 100%">
          <el-form-item label="基本信息:">
            <div>
              <el-form
                label-position="right"
                label-width="150px"
                style="margin-left: 0px !important"
              >
                <div style="width: 950px; text-align: center">
                  <img
                    v-if="sfzImage == null"
                    src="../../../public/img/carid.png"
                    height="100px"
                    width="100px"
                  />
                  <img v-else :src="sfzImage" height="100px" width="100px" />
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="姓名:" :prop="username">
                      <el-input
                        clearable
                        v-model="username"
                        placeholder="请输入姓名"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="身份证号:" prop="phone">
                      <el-input
                        v-model="user_code"
                        clearable
                        placeholder="请输入身份证号码"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="民族:" prop="phone">
                      <el-input
                        v-model="minzu"
                        clearable
                        placeholder="请输入民族"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="出生日期:" prop="work">
                      <div class="block">
                        <el-date-picker
                          @change="changedatetime($event)"
                          v-model="value1"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="选择日期"
                        >
                        </el-date-picker>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="年龄:" prop="age">
                      <el-input
                        v-model="age"
                        clearable
                        placeholder="请输入年龄"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号码:" prop="phone">
                      <el-input
                        v-model="mobile"
                        clearable
                        placeholder="请输入手机号码"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="文化程度:" prop="culture">
                      <el-input
                        v-model="learn_level"
                        clearable
                        placeholder="请输入文化程度"
                      ></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item
                      label="婚姻状况:"
                      prop="marriage"
                      class="radio"
                    >
                      <el-radio v-model="radio1" label="1" @change="getValue()"
                        >已婚</el-radio
                      >
                      <el-radio v-model="radio1" label="2" @change="getValue()"
                        >未婚</el-radio
                      >
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="性别:" class="radio" prop="radio3">
                      <el-radio v-model="radio3" label="1" @change="getValue()"
                        >男</el-radio
                      >
                      <el-radio v-model="radio3" label="2" @change="getValue()"
                        >女</el-radio
                      >
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="就业信息:" prop="work" class="radio">
                      <el-radio v-model="radio2" label="1" @change="getValue()"
                        >未就业</el-radio
                      >
                      <el-radio v-model="radio2" label="2" @change="getValue()"
                        >已就业</el-radio
                      >
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="就业意向:" prop="work">
                      <el-input
                        v-model="job_to"
                        clearable
                        placeholder="请输入就业意向"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12"> </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="身份证复印件:" prop="fujinImg">
                      <img
                        v-if="fujinImg == null"
                        src="../../../public/img/fuyin.png"
                        class="abcimg"
                      />
                      <img
                        v-else
                        :src="fujinImg"
                        style="width: 337px; height: 428px"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="半身照:" prop="work">
                      <img @click="callCamera" :src="cj" alt="摄像头" />

                      <!-- <el-upload
                        class="avatar-uploader"
                        :action="imgurl"
                        :multiple="false"
                        :show-file-list="false"
                        :on-progress="scs"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                      >
                        <img
                          v-if="aaaa"
                          style="width: 104px; height: 104px"
                          :src="'http://px.0123china.cn' + aaaa"
                          class="avatar"
                        />
                        <img v-else src="../../../public/img/half.png" alt="" />
                      </el-upload> -->
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <!-- 读卡器操作 -->
              <el-row :gutter="20" class="mb8" style="width: 100%">
                <el-col :span="8" style="text-align: right">
                  <el-button
                    type="success"
                    icon="el-icon-plus"
                    size="mini"
                    @click="connect"
                    >连接</el-button
                  >
                </el-col>
                <el-col :span="8">
                  <el-button
                    type="warning"
                    icon="el-icon-download"
                    size="mini"
                    @click="readCert"
                    >读卡</el-button
                  >
                </el-col>
                <el-col :span="8" style="text-align: left">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="disconnect"
                    >断开</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <div
              style="display: flex; justify-content: center; margin-top: 40px"
            >
              <el-form-item class="mb8">
                <el-button type="primary" @click="submitForm"
                  >添加学员</el-button
                >
                <el-button type="warning" @click="resetForm">重置</el-button>
              </el-form-item>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog title="拍照上传" :visible.sync="dialogVisible" width="950px">
      <div class="camera_outer">
        <div style="display: flex">
          <video
            id="videoCamera"
            :width="videoWidth"
            :height="videoHeight"
            style="width: 500px; height: 500px"
            autoplay
          ></video>
           <canvas
            style="display: none"
            id="canvasCamera"
            :width="videoWidth"
            :height="videoHeight"
          ></canvas>
          <div v-if="imgSrc" class="img_bg_camera">
             <img
              :src="imgSrc"
              alt=""
              class="tx_img"
              style="width: 500px; height: 500px"
            />
          </div>
        </div>
        <div style="margin-top: 20px;text-align: center;">
          <button @click="getCompetence()">打开摄像头</button>
          <button @click="stopNavigator()">关闭摄像头</button>
          <button @click="setImage()">拍照</button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import IdCard from "../../utils/idcard";
import axios from "axios";
export default {
  computed: {},
  data() {
    return {
      cj: require("../../../public/img/half.png"),
      videoWidth: 3000,
      videoHeight: 300,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      dialogVisible: false,
      headImgSrc: require("../../../public/img/carid.png"),
      value1: "", //出生日期时间控件
      //拍照
      videoWidth: 150,
      videoHeight: 150,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      radio1: "",
      radio2: "",
      radio3: "",

      username: "",
      user_code: "",
      imgurl: "",
      minzu: "",
      age: "",
      sex: "",
      card_img: "",
      birth: "",
      mer_status: "",
      mobile: "",
      learn_level: "",
      job_status: "",
      job_to: "",

      // 对话框的显隐
      showDialog: false,
      CertCtl: "",
      sfzImage: null, // 身份证照片
      // 查询参数
      IDCardForm: {
        name: "", // 姓名
        idCardNumber: "", // 身份证号码
        nation: "", // 民族
        birthday: "", // 出生日期
      },
      // 表单参数
      rules: {},
      timer: "",
      value: "",
      sTime: "",
      sfzpic: "",
      picc: "",
      avatarimg: "",
      aaaa: "",
      halfImg: "",
      userImg: "",
      fujinImg: null,
      fuyingImg: "",
      res: "",
      usercode: "",
    };
  },
  created() {
    // console.log(this.imgurl);
  },
  methods: {
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");
      this.thisContext = this.thisCancas.getContext("2d");
      this.thisVideo = document.getElementById("videoCamera"); // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      } // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象 // 使用getUserMedia，因为它会覆盖现有的属性。 // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia; // 有些浏览器不支持，会返回错误信息 // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          } // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function () {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {
          this.$notify.error({
            title: "摄像头开启失败",
            message: "请检查摄像头是否可用！",
          });
          console.log(err);
        });
    },
    //  绘制图片（拍照功能）
    setImage() {
      var _this = this; // 点击，canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      ); // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      console.log(image);
      _this.imgSrc = image;
      _this.cj = image;
      this.$emit("refreshDataList", this.imgSrc);
    },
    // base64转文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }, // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
    // 调用摄像头
    callCamera() {
      this.dialogVisible = true;
      //     this.$notify.error({
      //       title: "摄像头开启失败",
      //       message: "请检查摄像头是否可用！",
    },
    scs() {
      if (this.user_code == "") {
        this.$notify.error({
          title: "错误",
          message: "请输入身份证号",
        });
      }
      console.log(11111);
    },
    upTx() {
      var _this = this;
      var r = new FileReader();
      var file = document.getElementById("txUrl").files[0];
      console.log(document.getElementById("txUrl"));
      console.log(file);
      console.log(1111);
    },
    beforeAvatarUpload(file) {
      if ((this.user_code = null)) {
        console.log(22222);
      }
      //上传前的函数
      //上传前对图片类型和大小进行判断
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      // this.pic = res.pic//上传图片接口
      this.aaaa = res.pic;
      this.halfImg = res.pic;
      console.log(this.aaaa);
      console.log("res", res);
      console.log("file", file);
      this.picc = URL.createObjectURL(file.raw);
      console.log("this.picc", this.picc);
      // this.up_new(res.pic)
    },
    async up_new(data) {
      let res = await this.$api.home.up_new({
        file: data,
      });
      console.log(res);
    },
    //连接操作
    async connect() {
      // axios({
      //   method: "post",
      //   url: "http://127.0.0.1:18889/api/connect",
      // })
      //   .then(function (res) {
      //     console.log(res.data.name);
      //   })
      //   .catch(function (error) {
      //     alert("连接错误或驱动未安装")
      //   });
      let res = await IdCard.startConnect();
      if (res.resultFlag == 0) {
        this.$notify({
          title: "成功",
          message: res.errorMsg,
          type: "success",
        });
      }
    },
    //读卡操作
    async readCert() {
      let that = this;
      this.imgurl =
        "http://px.0123china.cn/api/v1.upload/up_new?user_code=" +
        this.user_code;
      let res = await IdCard.readCert();
      this.res = res.resultContent;
      this.sfzpic = res.resultContent.identityPic;
      console.log("ressss", res);
      let codeid = res.resultContent.certNumber;
      if (res.resultFlag == 0) {
        let a = await this.$api.home.checkArchive({
          user_code: codeid,
        });
        let is = a.data;
        console.log("is", is);
        if (is.code == 403) {
          this.$confirm("不在档案库中，是否录入?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              this.$message({
                type: "success",
                message: "确定录入",
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消录入",
              });
              this.sfzImage = "";
              this.fujinImg = "";
              this.username = "";
              this.user_code = "";
              this.minzu = "";
              this.value1 = "";
              this.radio3 = "";
            });
        }
        if (res.resultFlag == 0) {
          this.$notify({
            title: "成功",
            message: res.errorMsg,
            type: "success",
          });
        }
        let messagea = res.resultContent;
        console.log(messagea);
        console.log(messagea.identityPic);
        console.log(messagea.identityPrintPic);
        this.username = messagea.partyName;
        this.user_code = messagea.certNumber;
        this.minzu = messagea.nation;
        this.value1 = messagea.bornDay.replace(/(.{4})(.{2})/, "$1-$2-");
        if (messagea.gender == 0) {
          this.radio3 = "2";
        } else {
          this.radio3 = "1";
        }
        let getage = await this.$api.home.traineeAge({
          birthday: this.value1,
        });
        this.age = getage.data.data;
        console.log("getage", getage);
        that.sfzImage = "data:image/png;base64," + messagea.identityPic;
        that.fujinImg = "data:image/png;base64," + messagea.identityPrintPic;
      } else {
        this.$notify.error({
          title: "错误",
          message: res.errorMsg,
        });
      }
    },
    //断开连接
    async disconnect() {
      let res = await IdCard.disconnect();
      if (res.resultFlag == 0) {
        this.$notify({
          title: "成功",
          message: res.errorMsg,
          type: "success",
        });
      } else {
        this.$notify.error({
          title: "错误",
          message: res.errorMsg,
        });
      }
    },
    changedatetime(val) {
      this.sTime = val;
    },
    getValue() {
      this.sex = this.radio3;
      this.mer_status = this.radio1;
      this.job_status = this.radio2;
    },
    //添加学员
    async submitForm() {
      var fd = new FormData();
      var fda = new FormData();
      var hf = new FormData();
      let bsall;
      let bsalla;
      let bsallhf;

      if (this.res.identityPrintPic === undefined) {
        let filehfa = this.imgSrc;
        var fileshfa = this.dataURLtoFile(filehfa, "3.png");
        hf.append("file", fileshfa);
        bsallhf = (await this.$api.home.uploadUP(hf)).data;
        let add = (
          await this.$api.home.traineeAdd({
            username: this.username,
            user_code: this.user_code,
            minzu: this.minzu,
            age: this.age,
            sex: this.sex,
            birth: this.value1,
            mer_status: this.mer_status,
            mobile: this.mobile,
            learn_level: this.learn_level,
            job_status: this.job_status,
            job_to: this.job_to,
            // card_img: bsalla.pic,
            half_img: bsallhf.pic, //半身照
            // user_code_img: bsall.pic, //身份证复印照片
          })
        ).data;
        if (add.code == 200) {
          this.$notify({
            title: "成功",
            message: add.msg,
            type: "success",
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: add.msg,
          });
        }
      } else {
        console.log(222, this.res.identityPrintPic);
        console.log(this.imgSrc);
        let file = "data:image/png;base64," + this.res.identityPrintPic;
        let fileaa = "data:image/png;base64," + this.res.identityPic;
        let filehfa = this.imgSrc;
        var files = this.dataURLtoFile(file, "1.png");
        var filesaa = this.dataURLtoFile(fileaa, "2.png");
        var fileshfa = this.dataURLtoFile(filehfa, "3.png");
        fd.append("file", files);
        fda.append("file", filesaa);
        hf.append("file", fileshfa);
        bsall = (await this.$api.home.uploadUP(fd)).data;
        bsalla = (await this.$api.home.uploadUP(fda)).data;
        bsallhf = (await this.$api.home.uploadUP(hf)).data;
        let add = (
          await this.$api.home.traineeAdd({
            username: this.username,
            user_code: this.user_code,
            minzu: this.minzu,
            age: this.age,
            sex: this.sex,
            birth: this.value1,
            mer_status: this.mer_status,
            mobile: this.mobile,
            learn_level: this.learn_level,
            job_status: this.job_status,
            job_to: this.job_to,
            card_img: bsalla.pic,
            half_img: bsallhf.pic, //半身照
            user_code_img: bsall.pic, //身份证复印照片
          })
        ).data;
        if (add.code == 200) {
          this.$notify({
            title: "成功",
            message: add.msg,
            type: "success",
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: add.msg,
          });
        }
      }
    },
    dataURLtoFile(dataurl, filename) {
      //将base64转换为文件
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    //重置表单
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.username = "";
      this.user_code = "";
      this.minzu = "";
      this.age = "";
      this.radio3 = "";
      this.value1 = "";
      this.radio1 = "";
      this.mobile = "";
      this.learn_level = "";
      this.radio2 = "";
      this.job_to = "";
      this.sfzpic = "";
    },
  },
  // 重置表单
  reset() {},
};
</script>

<style lang="less" scope>
.entryFrom .el-form .el-row {
  width: 800px;
}
.abcimg {
  height: 300px;
  width: 200px;
}
.el-col-24 {
  width: 80%;
}
.entryFrom {
  display: flex;
  margin: 0 auto;
  .el-form {
    min-width: 500px;
    // text-align: center;
    .el-row {
      margin: 16px 0;
      .el-col {
        padding: 0;
      }
    }
  }
}
.el-form-item__content {
  width: 950px;
}
.img {
  text-align: center;
}
.titlep {
  text-align: center;
}
.mb8 {
  width: 100%;
  text-align: center;
}
.el-form-item {
  margin-bottom: 0;
}
.radio {
  text-align: left;
}
.el-input {
  width: 200px;
  text-align: left;
}

.select {
  width: 100%;
}
.camera_outer {
  position: relative;
  overflow: hidden;
  background-size: 100%;
  margin-top: 20px;
  // width: 80%;
  video,
  canvas,
  .tx_img {
    -moz-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    transform: scaleX(-1);
  }
  .btn_camera {
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
    height: 50px;
    background-color: rgba(0, 0, 0, 0.3);
    line-height: 50px;
    text-align: center;
    color: #ffffff;
  }
  .bg_r_img {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
  }
  .img_bg_camera {
    position: absolute;
    right: 30px;
    top: 0;
    img {
      width: 150px;
      height: 150px;
    }
    .img_btn_camera {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      color: #ffffff;
      .loding_img {
        width: 50px;
        height: 50px;
      }
    }
  }
}
.IMg {
  text-align: center;
}
.vdeo {
  width: 50%;
  margin: 0 auto;
}
</style>